const Layer = require('./layer')
const methods = require('methods');
function Route() {
    this.methods = {}
    this.stack = []; // 存放用户真实的回调逻辑
}
methods.forEach(method => {
    Route.prototype[method] = function (handlers) {
        this.methods[method] = true;  // 标识route中的方法有哪些
        handlers.forEach(fn => {
            let layer = new Layer('无需考虑', fn);
            layer.method = method
            this.stack.push(layer);
        });
    }
})

// app.route('/').get().post().delete()
Route.prototype.dispatch = function (req, res, out) {
    let idx = 0;
    const next = (err) => {
        if (err) {
            return out(err)
        }
        if (idx === this.stack.length) return out()
        let layer = this.stack[idx++];
        if (layer.method === req.method.toLowerCase()) {
            layer.handle_request(req, res, next); // 调用用户的回调
        } else {
            next();
        }
    }
    next();
}

module.exports = Route
